<template>
    <div class="container">
        <div id="mapContainer" class="mapContainer" :style="style">
        </div>
        <div class="search-container" v-if="isSearch">
            <div class="input-wrapper">
                <span class="search-label">搜索</span> <input id="searchText" type="text" class="search-text" placeholder="请输入搜索词" />
            </div>
        </div>
    </div>
</template>

<script>
    import {lazyAMapApiLoaderInstance} from 'vue-amap';

    export default {
        name: "amap-store",
        data() {
            return {
                searchText: '',
                style: {
                    width: this.width,
                    height: this.height
                }
            };
        },
        props: {
            width:{
                type: String,
                default: '100vw'
            },
            height:{
                type: String,
                default: '100vh'
            },
            // 当前经纬度坐标
            center:{
                type: Array,
                default: () => {
                    return [];
                }
            },
            //自提点经纬度坐标 [123.45,80.34]
            position: {
                type: Array,
                default: () => {
                    return [];
                }
            },
            //缩放级别
            zoom: {
                type: Number,
                default: 16
            },
            //模式:可选'normal'(显示商店定位)、'positionPicker'(商店位置拖拽选择)
            mode: {
                type: String,
                default: 'normal'
            },
            //是否加载POI搜索
            isSearch: {
                type: Boolean,
                default: false
            },
        },
        mounted() {
            //初始化加载地图
            lazyAMapApiLoaderInstance.load().then(() => {
                let option = {};
                if (this.center.length) {
                    option.center = this.center;
                }
                if (this.zoom) {
                    option.zoom = this.zoom;
                }
                option.scrollWheel = false;
                this.map = new AMap.Map('mapContainer', option);
                this.AMap = AMap;
                //加载poi搜索组件
                if (this.isSearch) {
                    this._initPoiPicker(AMapUI);
                }

                if (this.mode === 'positionPicker') {
                    this._initPositionPicker(AMapUI);
                } else {
                    //normal模式 只显示position位置或者设备当前定位位置
                    if (!this.center.length) {
                        //未传location定位当前设备位置
                        this._getCurrentPositon();
                    } else {
                        this.addMarker(this.center);
                        this.addMoreMaker()
                    }
                }
            });
        },
        methods: {
            addMoreMaker(){
                // var map = new AMap.Map('mapContainer', {
                //     resizeEnable: true,
                //     center: this.center,
                //     zoom: 15
                // });
                // map.clearMap();  // 清除地图覆盖物

                // var markers = [{
                //     icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-1.png',
                //     position: [118.52642,37.45741]
                // }, {
                //     icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-2.png',
                //     position: [118.52967,37.45521]
                // }, {
                //     icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-3.png',
                //     position: [118.52398,37.45775]
                // }];
                let map = this.map;
                // 添加一些分布不均的点到地图上,地图上添加三个点标记，作为参照
                this.position.forEach(function(marker,index) {
                    new AMap.Marker({
                        map: map,
                        // icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-'+index+'.png',
                        position: [marker[0], marker[1]],
                        offset: new AMap.Pixel(-13, -30)
                    });
                });
                // 添加事件监听, 使地图自适应显示到合适的范围
                var newCenter = map.setFitView();
            },
            addMarker(position, message) {
                const AMap = this.AMap;
                const map = this.map;
                // 创建一个 Marker 实例
                var marker = new AMap.Marker({
                    position: new AMap.LngLat(...position), // 经纬度构成的一维数组[116.39, 39.9]
                    title: ''
                });
                // 将创建的点标记添加到已有的地图实例
                map.add(marker);

                //处理InfoWindow
                if (message) {
                    let infoWindow = new AMap.InfoWindow({
                        position: position,
                        offset: new AMap.Pixel(0, -20), //纵向偏移
                        showShadow: true, //显示阴影
                        content: message //文字内容
                    });

                    infoWindow.open(map);
                }

                this.map.setCenter(marker.getPosition());
                var circle = new AMap.Circle({
                    map: map,
                    center: position,          //设置线覆盖物路径
                    radius: 1000,
                    strokeColor: "#3366FF", //边框线颜色
                    strokeOpacity: 0.3,       //边框线透明度
                    strokeWeight: 3,        //边框线宽
                    fillColor: "#FFA500", //填充色
                    fillOpacity: 0.35//填充透明度
                });
            },
            //初始化拖拽选择
            _initPositionPicker(AMapUI) {
                //加载拖拽选择插件 positionPicker
                AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
                    var positionPicker = new PositionPicker({
                        mode: 'dragMap', //设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
                        map: this.map //依赖地图对象
                    });
                    positionPicker.on('success', (positionResult) => {
                        // console.log(positionResult);
                        this.$emit('selectLocation', positionResult);
                    });
                    positionPicker.on('fail', (positionResult) => {
                        console.info(positionResult);
                    });
                    //开始拖拽选择
                    positionPicker.start();
                });
            },
            //初始化poi搜索
            _initPoiPicker(AMapUI) {
                //加载拖拽选择插件 PoiPicker
                AMapUI.loadUI(['misc/PoiPicker'], (PoiPicker) => {
                    var poiPicker = new PoiPicker({
                        input: 'searchText' //输入框id
                    });
                    //监听poi选中信息
                    poiPicker.on('poiPicked', (poiResult) => {
                        //用户选中的poi点信息
                        let poi = poiResult.item;
                        this.addMarker([poi.location.lng, poi.location.lat], poi.name);
                    });
                });
            },
            _getCity() {
                if (!this.AMap) {
                    return;
                }
                const AMap = this.AMap;
                AMap.plugin('AMap.CitySearch', () => {
                    const citySearch = new AMap.CitySearch();
                    citySearch.getLocalCity((status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            // 查询成功，result即为当前所在城市信息
                            console.log('amap-_getCity',result);
                        }
                    });
                });
            },
            _getCurrentPositon() {
                const AMap = this.AMap;
                const map = this.map;
                var geolocation = new AMap.Geolocation({
                    // 是否使用高精度定位，默认：true
                    enableHighAccuracy: false,
                    // 设置定位超时时间，默认：无穷大
                    timeout: 10000,
                    // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                    buttonOffset: new AMap.Pixel(10, 20),
                    //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    zoomToAccuracy: true,
                    //  定位按钮的排放位置,  RB表示右下
                    buttonPosition: 'RB'
                });

                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', (data) => {
                    console.log('amap-addListener',data);
                });
                AMap.event.addListener(geolocation, 'error', (err) => {
                    console.log('amap-addListener-err',err);
                });
                map.addControl(geolocation);
            },
        }
    };
</script>
<style lang="stylus" scoped>
    @import '~assets/main.styl'

    .container{
        position relative
        .mapContainer {
            position relative
            >>> .amap-logo{
                display: none;
                opacity:0 !important;
            }
            >>> .amap-copyright {
                opacity:0;
            }
        }
        .search-container{
            position fixed
            top vw(20)
            left vw(20)
            width vw(250)
            background-color grayF
            padding smallMargin smallMargin
            border-radius radius
            min-width vw(20)
            border-width 0
            box-shadow 0 2px 6px 0 rgba(114, 124, 245, .5)
            .input-wrapper{
                display flex
                justify-content center
                .search-label{
                    line-height vw(15)
                    flex 0 0 vw(40)
                    padding titleMargin titleMargin
                    display inline-block
                    font-size word12
                    font-weight bold
                    color grayF
                    background-color main-color
                    border 1px solid main-color
                    text-align center
                }
                .search-text{
                    flex 0 1 vw(200)
                    border 1px solid main-color
                    padding titleMargin titleMargin
                    font-size word12
                    line-height vw(15)
                }
            }
        }
    }
</style>
